<template>
  <div class="login">
    <div class="box">
      <h2>后台管理系统</h2>
      <el-form ref="formRef" style="max-width: 600px;" :model="formData" status-icon :rules="rules" label-width="auto">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" type="password" />
        </el-form-item>

        <el-form-item style="justify-content: center;">
          <el-button type="primary" @click="submitForm(formRef)">
            登录
          </el-button>
          <el-button @click="resetForm(formRef)">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang='ts'>
//导入组合式API
import { reactive, ref } from 'vue'
//导入路由器
import { useRouter } from 'vue-router'
//导入element-plus的类型
import type { FormInstance, FormRules } from 'element-plus'
//导入请求API
import { $Login } from '@/api/admin'
//返回路由器对象
const router =useRouter()

//定义一个ref对象绑定表单
const formRef = ref<FormInstance>()

//表单数据
const formData = reactive({
  username: 'dev2',
  password: '123456',
})
//登录状态
const loginStatus = ref(true)


//验证用户名
const validateUsername = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入用户名'))
  } else {
    callback()
  }
}
//验证密码
const validatePassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    callback()
  }
}


//验证对象
const rules = reactive<FormRules<typeof formData>>({
  username: [{ validator: validateUsername, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }],
})

//提交表单
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async(valid) => {
    //TODO 添加加载状态，防止重复提交
    if (valid) {
      const ret = await $Login(formData)
      if(ret){
        router.push('/home')
      }
    } else {
      console.log('error submit!')
    }
  })
}

//重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style scoped lang="scss">
.login {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(to bottom, #5D7B8B, #F5F0E6);
  display: flex;
  justify-content: center;
  align-items: center;

  .box {
    width: 400px;
    height: 250px;
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;

    h2 {
      text-align: center;
      //对应父容器的padding
      margin-bottom: 20px;
      font-family: 月星楷-bold;
    }

    :deep(.el-form-item__content) {
      justify-content: center;
    }

  }
}
</style>
